const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const xmlparser = require('express-xml-bodyparser');
const compression = require('compression');
const expressWinston = require('express-winston');
const cors = require('cors');
const logger = require('./utils/logger');
const routes = require('./routes');

const { isJSON } = require(__util + "/help");
const ErrorCode = require(__util + "/errcode")


const app = express();
app.use(cors());

app.use(expressWinston.logger({
  winstonInstance: logger,
  meta: false,
  expressFormat: true,
}));

app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(xmlparser({
  normalize: false,
  normalizeTags: false
}));

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(routes);

// express 路由错误处理(可以捕获路由中next出来的错误, 对以前的所有接口皆无影响, 该方法只会捕获路由中主动next()出来的错误)
app.use((err, req, res, next) => {
  // 判断是否为结构化的错误
  if (isJSON(err.message)) {
    res.json(JSON.parse(err.message));
  } else {
    res.json(ErrorCode.SYSTEM_BUSY); // 若为其他非结构化的错误, 抛出系统繁忙, 保证前端响应, 并记录日志
    logger.error(err); // 日志输出错误
  }
});



module.exports = app;
